package com.supinfo.suptracking.servlet;

import com.supinfo.suptracking.entity.Car;
import com.supinfo.suptracking.entity.Gpspositionhistory;
import com.supinfo.suptracking.service.CarService;
import com.supinfo.suptracking.service.GpsPositionHistoryService;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Fabien, Jérémy, Ludovic, Brice
 */

@WebServlet(name = "RemoveCarServlet", urlPatterns = {"/auth/removeCar"})
public class RemoveCarServlet extends HttpServlet {

    @EJB
    private CarService carServ;
    
    @EJB
    private GpsPositionHistoryService gpsServ;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get form fields
        String carIdTemp = request.getParameter("carIdRemove");
        
        // Transform id in long
        Long carId=Long.valueOf(carIdTemp);

        // Remove pos gps of the car
        Car cardel = carServ.processGetCarById(carId);
        List<Gpspositionhistory> gpsList = gpsServ.processGetAllPositionHistoryByCar(cardel);
        if(!gpsList.isEmpty()){
            gpsList.stream().forEach((gpsPos) -> {
                gpsServ.processdelPositionHistory(gpsPos.getId());
            });
        }
                 
        // Remove car
        carServ.processDelCar(cardel);
         
        // Notification of user and redirect
        request.getSession().setAttribute("event", "1");
        request.getSession().setAttribute("message", "Car deleted");
        response.sendRedirect(getServletContext().getContextPath()+"/auth/listCar");
    }
}
